﻿#include "TestTrayIcon.h"
#include <QMessageBox>
#include <QCloseEvent>
#include <QPushButton>
TestTrayIcon::TestTrayIcon(QWidget* parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    setWindowFlag(Qt::Window);
    setWindowFlag(Qt::WindowMinimizeButtonHint, true);
    setWindowFlag(Qt::WindowCloseButtonHint, true);
    //托盘初始化
    QIcon icon = QIcon("icon.png");
    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(icon);
    trayIcon->setToolTip("a trayicon example");
    trayIcon->show(); //必须调用，否则托盘图标不显示

    //创建菜单项动作(以下动作只对windows有效)
    minimizeAction = new QAction("最小化~", this);
    connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide())); //绑定信号槽

    maximizeAction = new QAction("最大化~", this);
    connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));

    restoreAction = new QAction("还原~", this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));

    quitAction = new QAction("退出~", this);
    connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); //关闭应用，qApp对应的是程序全局唯一指针

    //创建托盘菜单(必须先创建动作，后添加菜单项，还可以加入菜单项图标美化)
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(minimizeAction);
    trayIconMenu->addAction(maximizeAction);
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(quitAction);
    trayIcon->setContextMenu(trayIconMenu);

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
        this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
}

TestTrayIcon::~TestTrayIcon()
{
}

void TestTrayIcon::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {
    case QSystemTrayIcon::Trigger:
        trayIcon->showMessage("title", "你单击了"); //后面两个默认参数
        break;
    case QSystemTrayIcon::DoubleClick:
        trayIcon->showMessage("title", "你双击了");
        break;
    case QSystemTrayIcon::MiddleClick:
        trayIcon->showMessage("title", "你中键了");
        hide();
        break;
    default:
        break;
    }
}